package com.github.bitsapling.sapling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.bitsapling.sapling.mapper.PermissionMapper;
import com.github.bitsapling.sapling.mapper.UserGroupMapper;
import com.github.bitsapling.sapling.mapper.UserGroupPermissionMapper;
import com.github.bitsapling.sapling.entity.*;
import com.github.bitsapling.sapling.service.UserGroupService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class UserGroupServiceImpl implements UserGroupService {
    @Resource
    private UserGroupMapper userGroupMapper;

    @Resource
    private UserGroupPermissionMapper userGroupPermissionMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserGroup getDefaultUserGroup() {
        return userGroupMapper.selectOne(
                new QueryWrapper<UserGroup>().eq("slug", "levelZero")
        );
    }

    @Override
    public List<String> getPermissionSlugsById(Long groupId) {
        // 获取用户组关联的权限 ID 列表
        List<UserGroupPermission> permissionIds = userGroupPermissionMapper.selectList(
                new QueryWrapper<UserGroupPermission>().eq("user_group_id", groupId)
        );
        log.info("permissionIds:{}",permissionIds);
        if (permissionIds.isEmpty()) {
            return List.of();
        }
        // 提取 permissionIds 列表中的 permissionId 字段
        List<Long> permissionIdList = permissionIds.stream()
                .map(UserGroupPermission::getPermissionId)
                .collect(Collectors.toList());
        // 获取权限信息列表
        List<Permission> permissions = permissionMapper.selectList(
                new QueryWrapper<Permission>().in("id", permissionIdList)
        );
        // 将权限的 slug 收集成列表返回
        return permissions.stream()
                .map(Permission::getSlug)
                .collect(Collectors.toList());
    }

    @Override
    public String getGroupSlugById(Long groupId) {
        UserGroup userGroup = userGroupMapper.selectById(groupId);
        return userGroup.getSlug();
    }
}
